package xyz.tanxiao.links.controller;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import xyz.tanxiao.links.common.ResponseResult;
import xyz.tanxiao.links.common.ValidationUtils;
import xyz.tanxiao.links.common.enums.LimitTargetEnum;
import xyz.tanxiao.links.common.exception.ToShortLinkException;
import xyz.tanxiao.links.common.request.ToShortLinkRequest;
import xyz.tanxiao.links.core.limit.SimpleAccessLimit;
import xyz.tanxiao.links.core.limit.SimpleAccessLimits;
import xyz.tanxiao.links.service.SlLinkMappingService;

import java.util.concurrent.TimeUnit;


/**
 * 生成短链控制器
 *
 * @author 万成波
 * @email 2300064869@qq.com
 * @createTime 2023-06-11 04:17:03 星期日
 */
@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/links")
public class LinksGenerateController {

	private final SlLinkMappingService linkMappingService;


	/**
	 * 长链接转为短链接
	 *
	 * @param request 请求参数
	 * @return 短链接
	 */
	@SimpleAccessLimits({
		@SimpleAccessLimit(target = LimitTargetEnum.TO_SHORT_LINK, level = 1, time = 10, timeUnit = TimeUnit.SECONDS, count = 6),
		@SimpleAccessLimit(target = LimitTargetEnum.TO_SHORT_LINK, level = 2)
	})
	@PostMapping("/short")
	public ResponseResult toShortLink(@RequestBody ToShortLinkRequest request) {
		log.info("=> 原始长连接：{}", request.getSourceUrl());
		try {
			ValidationUtils.validate(request, ValidationUtils.ThrowTypeEnum.FIRST);
		} catch (Exception e) {
			throw new ToShortLinkException(e.getMessage());
		}
		String shortLink = this.linkMappingService.toShortLink(request);
		return ResponseResult.success().data(shortLink);
	}

}